package com.thd.kc;

import com.thd.kc.service.KcService;
import com.thd.kc.utils.FileUtils;
import com.thd.kc.utils.LuceneUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.*;
import java.nio.file.Path;


@SpringBootApplication(scanBasePackages = "com.thd")
public class Application extends SpringBootServletInitializer {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }

    public static void main(String[] args) throws Exception{

        /**
         * 拷贝数据库文件
         */
        String jarPathStr = System.getProperty("user.dir");
        logger.info("jar file path : " + jarPathStr);

        Path jarPath = new File(jarPathStr).toPath();

        String targetDbFilePath = jarPathStr + File.separator + "kc.db";

        File f = new File(targetDbFilePath);
        logger.info("===================== prepare to copy db file=============================");
        if(!f.exists()){
            logger.info(targetDbFilePath + " file not exist , create db file ");
            InputStream inputStream = Application.class.getClassLoader().getResourceAsStream("db/kc.db");
            if(null == inputStream){
                throw new Exception("db file not be found!");
            }
            logger.info("1. obtain db file success : "+ inputStream);

//        Path tempFile = Files.createTempFile("mySqlLiteDb", ".db");
//        System.out.println(tempFile);
//        logger.info("2. db temp file created success ");
//
//        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
//        logger.info("2. db temp file initial success, " + tempFile);

//        String jarPath = Application.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//        System.out.println("jar路径：" +jarPath );

//        URI jarUri = Application.class.getProtectionDomain()
//                .getCodeSource().getLocation().toURI();
//        System.out.println("jar路径：" +jarUri );


            String jarName = System.getProperty("java.class.path");
            System.out.println("java.class.path：" + jarName );



            logger.info("2. target db file path : " + targetDbFilePath);
            FileUtils.writeFile(inputStream, targetDbFilePath);
            logger.info("3. db temp file initial success: " + targetDbFilePath.toString());





        }else{
            logger.info("db file is existed  ");
        }


        String luceneIndexPath = jarPathStr + File.separator + "lucene_index";
        logger.info("lucene index path : " + luceneIndexPath);
        LuceneUtils.initGlobal(luceneIndexPath);


        // 启动服务
        ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
//        String[] names = ctx.getBeanDefinitionNames();

        // 初始化索引

        File luceneIndexFolder = new File(luceneIndexPath);
        File[] indexFiles = luceneIndexFolder.listFiles();
        if(indexFiles == null || indexFiles.length == 0){
            logger.info("Lucene Index Files Not Existed , Creating ... : " + luceneIndexPath.toString());
            LuceneUtils.initIndex();
        }else{
            logger.info("Lucene Index Files Existed :  " + luceneIndexPath.toString());
        }

    }
}
